import {createRouter, createWebHistory} from "vue-router"
import Login from "../views/Login.vue"
import Layout from "../components/Layout.vue"
import UserList from "../views/UserList.vue"
import HospitalList from "../views/HospitalList.vue"
import LogList from "../views/LogList.vue"

const routes = [
    {
        path: "/login",
        name: "Login",
        component: Login,
    },
    {
        path: "/",
        component: Layout,
        redirect: "/users",
        children: [
            {
                path: "users",
                name: "UserList",
                component: UserList,
                meta: {title: "用户管理"},
            },
            {
                path: "hospitals",
                name: "HospitalList",
                component: HospitalList,
                meta: {title: "医院管理"},
            },
            {
                path: "logs",
                name: "LogList",
                component: LogList,
                meta: {title: "操作日志"},
            },
        ],
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = sessionStorage.getItem("token")
    if (to.path !== "/login" && !token) {
        next("/login")
    } else if (to.path === "/login" && token) {
        next("/")
    } else {
        next()
    }
})

export default router